package com.sxjh.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxjh.common.Constant;
import com.sxjh.entity.PlannedOrdersEntity;
import com.sxjh.entity.param.PlannedOrderListParam;
import com.sxjh.entity.param.ReportsDetailParam;
import com.sxjh.mapper.PlannedOrdersMapper;
import com.sxjh.mapper.TaskMapper;
import com.sxjh.service.PlannedOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 内部倒运-计划单表 服务实现类
 * </p>
 *
 * @author guanxy
 * @since 2023-05-31
 */
@Slf4j
@Service
public class PlannedOrdersServiceImpl extends ServiceImpl<PlannedOrdersMapper, PlannedOrdersEntity>
        implements PlannedOrdersService {

    @Autowired
    PlannedOrdersMapper plannedOrdersMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Override
    public IPage<PlannedOrderListParam> queryPage(IPage iPage, PlannedOrderListParam param) {
        IPage<PlannedOrderListParam> page = plannedOrdersMapper.queryPage(iPage, param);
        if (page != null && CollUtil.isNotEmpty(page.getRecords())) {
            ReportsDetailParam param11 = new ReportsDetailParam();
            IPage iipage = new Page(1, Constant.maxSize);
            param11.setPlannedOrderIdList(page.getRecords().stream().map(PlannedOrderListParam::getId).collect(Collectors.toList()));
            param11.setStatusList(param.getStatusList());
            IPage<ReportsDetailParam> detailPage = taskMapper.taskDetailList(iipage, param11);
            if (detailPage != null && CollUtil.isNotEmpty(detailPage.getRecords())) {
                page.getRecords().forEach(p -> {
                    List<ReportsDetailParam> detailList = detailPage.getRecords().stream()
                            .filter(d -> p.getId().intValue() == d.getPlannedOrderId() && d.getNetCount() != null).map(d -> {
                                if (d.getNetCount() != null) {
                                    d.setNetCount((new BigDecimal(d.getNetCount())).divide(BigDecimal.valueOf(1000L)).doubleValue());
                                }
                                return d;
                            }).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(detailList)) {
                        p.setCompleteTotal(detailList.stream().filter(t -> t.getNetCount() != null).mapToDouble(ReportsDetailParam::getNetCount).sum());
                    }
                });
            }
        }
        return page;
    }
}
